<script setup lang="ts">
  import { computed, ref, watch } from 'vue';
  import { RouteRecordRaw, useRoute } from 'vue-router';
  import { useMultipleTabs } from '@/store/module/useMultipleTabsStore';
  import { useGo } from '@/hooks/router';
  import { useLocale } from '@/locales/useLocale';

  const route = useRoute();
  const go = useGo();
  const multipleTabsStore = useMultipleTabs();
  const { t } = useLocale();
  const currentTab = ref('');
  watch(
    route,
    (value) => {
      if (value.fullPath.includes('/datashow')) {
        currentTab.value = value.fullPath;
        multipleTabsStore.addTab({
          title: value.meta.title as string,
          name: value.fullPath,
        });
      }
    },
    { deep: true, immediate: true }
  );

  const clickTab = (e: any) => {
    if (currentTab.value === route.fullPath) {
      return;
    }
    go(e.props.name);
  };
  const removeTab = (name: string) => {
    if (multipleTabsStore.data.length === 1) {
      return;
    }
    let currentIndex = multipleTabsStore.data.findIndex((value) => {
      return value.name === name;
    });
    let nextIndex =
      currentIndex === multipleTabsStore.data.length - 1 ? currentIndex - 1 : currentIndex + 1;
    let nextTab = multipleTabsStore.data[nextIndex];
    multipleTabsStore.removeTab(name);
    if (name === route.fullPath) {
      go(nextTab.name as unknown as RouteRecordRaw);
    }
  };
</script>

<template>
  <div class="flex-1 multiple-tabs lg:px-2 overflow-x-auto hidden-scrollbar" id="multiple-tabs">
    <el-tabs
      v-model="currentTab"
      type="card"
      closable
      @tab-remove="removeTab"
      @tab-click="clickTab"
    >
      <el-tab-pane v-for="item in multipleTabsStore.data" :key="item.name" :name="item.name">
        <template #label>
          {{ t(item.title) }}
        </template>
      </el-tab-pane>
    </el-tabs>
  </div>
</template>

<style lang="scss">
  .multiple-tabs {
    .el-tabs__header {
      @apply m-0;
    }
    .el-tabs--card > .el-tabs__header {
      @apply dark:border-border-b-dark;
    }
    .el-tabs__item {
      @apply dark:text-main-text-dark border-border-b dark:border-border-b-dark h-[30px] leading-[30px] lg:h-[40px] lg:leading-[40px] lg:px-[20px];
    }
    .el-tabs__nav {
      @apply border-border-b dark:border-border-b-dark;
    }
    .el-tabs__item.is-active {
      @apply text-menu-active-text dark:text-menu-active-text-dark border-border-b dark:border-border-b-dark;
    }
  }
  #multiple-tabs {
    .el-tabs__item {
      @apply h-[30px] leading-[30px] px-[15px] lg:h-[40px] lg:leading-[40px] lg:px-[20px];
    }
  }
</style>
